package com.qixin.modules.eaApplication.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qixin.modules.eaApplication.entity.EaBusinessApply;
import com.qixin.modules.eaApplication.entity.EaBusinessPerDtl;
import com.qixin.modules.eaApplication.service.IEaBusinessApplyService;
import com.qixin.modules.eaApplication.service.IEaBusinessPerDtlService;
import com.qixin.modules.eaApplication.vo.EaBusinessApplyPage;
import com.qixin.modules.eaApplication.vo.EaBusinessApplyPrintVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.activity.service.ActivityCommonService;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 出差申请单
 * @Author: qixin-boot
 * @Date:   2022-01-21
 * @Version: V1.0
 */
@Api(tags="出差申请单")
@RestController
@RequestMapping("/eaApplication/eaBusinessApply")
@Slf4j
public class EaBusinessApplyController {
	@Autowired
	private IEaBusinessApplyService eaBusinessApplyService;
	@Autowired
	private IEaBusinessPerDtlService eaBusinessPerDtlService;
	@Autowired
	private INcPersonnelService ncPersonnelService;
	// 工作流公共执行类
	@Autowired
	private ActivityCommonService activityCommonService;
	
	/**
	 * 分页列表查询
	 *
	 * @param eaBusinessApply
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="出差申请单-分页列表查询", notes="出差申请单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(EaBusinessApply eaBusinessApply,
								   @RequestParam(name="billDateBegin", required = false) String billDateBegin,
								   @RequestParam(name="billDateEnd", required = false) String billDateEnd,
								   @RequestParam(name="userid", required = false) String userid,
								   @RequestParam(name="billCode", required = false) String billCode,
								   @RequestParam(name="isUse", required = false) String isUse,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<EaBusinessApply> queryWrapper = QueryGenerator.initQueryWrapper(eaBusinessApply, req.getParameterMap());
		if (StringUtils.isNotBlank(billDateBegin)){
			// 大于等于开始日期
			queryWrapper.ge("bill_date", billDateBegin);
		}
		if (StringUtils.isNotBlank(billDateEnd)){
			// 小于等于结束日期
			queryWrapper.le("bill_date", billDateEnd);
		}
		//add-begin-by wujinbiao 2022-01-29 for 添加查询条件 列表排序，创建人
		queryWrapper.orderByDesc("create_time");
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(isUse == null){
			queryWrapper.and(
					wrapper -> wrapper.eq("create_by",loginUser.getId()).or().eq("person_id",loginUser.getPkPsndoc())
			);
		}
		if(StringUtils.isNotBlank(isUse) && "1".equals(isUse)){
			// 关联报销单时用到
			queryWrapper.eq("if_changed",0);
			// 过滤被报销的出差申请单
			queryWrapper.and(
				p -> p.isNull("ea_travel_id").or().eq("ea_travel_id","")
			);
			if (StringUtils.isNotBlank(userid)){
				queryWrapper.eq("person_id", userid);
			}
		}
		if(StringUtils.isNotBlank(billCode)){
			// 单据编号模糊查询
			queryWrapper.like("bill_no",billCode);
		}
		//add-end-by wujinbiao 2022-01-29 for 添加查询条件

		Page<EaBusinessApply> page = new Page<EaBusinessApply>(pageNo, pageSize);
		IPage<EaBusinessApply> pageList = eaBusinessApplyService.page(page, queryWrapper);
		//add-begin-by wujinbiao for 返回申请人中文名称
		List<EaBusinessApply> records = pageList.getRecords();
		for (EaBusinessApply eaBusinessApply1: records) {
			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApply1.getPersonId());
			if(ncPersonnel != null){
				eaBusinessApply1.setPersonIdName(ncPersonnel.getName());
			}
		}
		//add-end-by wujinbiao for 返回申请人中文名称
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param eaBusinessApplyPage
	 * @return
	 */
	@AutoLog(value = "出差申请单-添加")
	@ApiOperation(value="出差申请单-添加", notes="出差申请单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody EaBusinessApplyPage eaBusinessApplyPage) {

		EaBusinessApply eaBusinessApply = new EaBusinessApply();
		BeanUtils.copyProperties(eaBusinessApplyPage, eaBusinessApply);

		// update-begin-Autor: wmf date: 2022-02-08 11:42 for: 生成单据编号
		JSONObject jsonObj = new JSONObject();
		if (StringUtils.isNotBlank(eaBusinessApply.getParentId())){
			jsonObj.put("prefix","CCBG");
		}else{
			jsonObj.put("prefix","CCSQ"); // 编码前缀
		}
		Object result = FillRuleUtil.executeRule("common_code", jsonObj);
		eaBusinessApply.setBillNo(result.toString());

		// update-end-Autor: wmf date: 2022-02-08 11:42 for: 生成单据编号

		// 设置单据的状态为未提交
		eaBusinessApply.setState(0);
		eaBusinessApplyService.saveMain(eaBusinessApply, eaBusinessApplyPage.getEaBusinessPerDtlList());
		//update-begin-Autor：wjb 2022-02-07  for 返回主表、子表数据给前端
		EaBusinessApplyPage resultPage = new EaBusinessApplyPage();
		BeanUtils.copyProperties(eaBusinessApply,resultPage);
		resultPage.setEaBusinessPerDtlList(eaBusinessApplyPage.getEaBusinessPerDtlList());
		//update-end-Autor：wjb 2022-02-07  for 返回主表、子表数据给前端

		return Result.OK(resultPage);
	}
	
	/**
	 *  编辑
	 *
	 * @param eaBusinessApplyPage
	 * @return
	 */
	@ApiOperation(value="出差申请单-编辑", notes="出差申请单-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody EaBusinessApplyPage eaBusinessApplyPage) {
		EaBusinessApply eaBusinessApply = new EaBusinessApply();
		BeanUtils.copyProperties(eaBusinessApplyPage, eaBusinessApply);
		EaBusinessApply eaBusinessApplyEntity = eaBusinessApplyService.getById(eaBusinessApply.getId());
		if(eaBusinessApplyEntity==null) {
			return Result.error("未找到对应数据");
		}
		eaBusinessApplyService.updateMain(eaBusinessApply, eaBusinessApplyPage.getEaBusinessPerDtlList());
		return Result.OK(eaBusinessApplyPage);
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出差申请单-通过id删除")
	@ApiOperation(value="出差申请单-通过id删除", notes="出差申请单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		QueryWrapper<EaBusinessApply> params = new QueryWrapper<>();
		params.eq("id",id);
		EaBusinessApply eaBusinessApply = eaBusinessApplyService.getOne(params);
		if (eaBusinessApply != null && eaBusinessApply.getState()>0){
			return Result.error("该单据已发起流程,不可删除!");
		}
		eaBusinessApplyService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出差申请单-批量删除")
	@ApiOperation(value="出差申请单-批量删除", notes="出差申请单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.eaBusinessApplyService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出差申请单-通过id查询")
	@ApiOperation(value="出差申请单-通过id查询", notes="出差申请单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {

		EaBusinessApplyPage eaBusinessApplyPage = new EaBusinessApplyPage();
		EaBusinessApply eaBusinessApply = eaBusinessApplyService.getById(id);
		if(eaBusinessApply==null) {
			return Result.error("未找到对应数据");
		}
		//update-begin-by wujinbiao for 详情返回申请人名称
		if(StringUtils.isNotBlank(eaBusinessApply.getPersonId())){
			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApply.getPersonId());
			eaBusinessApply.setPersonIdName(ncPersonnel.getName());
		}
		//update-end-by wujinbiao for 详情返回申请人名称
		BeanUtils.copyProperties(eaBusinessApply,eaBusinessApplyPage);
		//添加出行人员明细
		List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(id);
		eaBusinessApplyPage.setEaBusinessPerDtlList(eaBusinessPerDtlList);
		return Result.OK(eaBusinessApplyPage);
	}

	 /**
	 * @Description 出差申请单打印模板-通过id查询
	 * @author  wujinbiao
	 * @date 2022/2/9 09:30
	 * @param id
	 * @return org.jeecg.common.api.vo.Result<?>
	 */
	 @AutoLog(value = "出差申请单打印模板-通过id查询")
	 @ApiOperation(value="出差申请单打印模板-通过id查询", notes="出差申请单打印模板-通过id查询")
	 @GetMapping(value = "/selectById")
	 public Result<?> selectById(@RequestParam(name="id",required=true) String id) {
		 EaBusinessApplyPrintVo eaBusinessApplyPrintVo = new EaBusinessApplyPrintVo();
		 EaBusinessApply eaBusinessApply = eaBusinessApplyService.getById(id);
		 if(eaBusinessApply==null) {
			 return Result.error("未找到对应数据");
		 }
		 if(StringUtils.isNotBlank(eaBusinessApply.getPersonId())){
			 NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApply.getPersonId());
			 eaBusinessApply.setPersonIdName(ncPersonnel.getName());
		 }
		 BeanUtils.copyProperties(eaBusinessApply,eaBusinessApplyPrintVo);
		 //添加出行人员明细
		 List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(id);
		 if(eaBusinessPerDtlList.size()>0){
			 for (EaBusinessPerDtl eaBusinessPerDtl:eaBusinessPerDtlList) {
				 if (StringUtils.isNotBlank(eaBusinessPerDtl.getPersonnel())){
					 NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessPerDtl.getPersonnel());
					 if(ncPersonnel != null){
						 eaBusinessPerDtl.setPersonnelName(ncPersonnel.getName());
					 }
				 }
			 }
		 }
		 eaBusinessApplyPrintVo.setEaBusinessPerDtlList(eaBusinessPerDtlList);
		 // update-begin-Autor: Wengmf date: 2022-02-10 10:42 for: 添加流程审批记录
		 if (StringUtils.isNotBlank(eaBusinessApply.getProcInstId())){
			 List<Map<String, Object>> nodeList = activityCommonService.getNodeList(eaBusinessApply.getProcInstId());
			 eaBusinessApplyPrintVo.setSpjl(nodeList);
		 }
		 // update-end-Autor: Wengmf date: 2022-02-10 10:42 for: 添加流程审批记录
		 return Result.OK(eaBusinessApplyPrintVo);
	 }

	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="出行人-主表ID查询", notes="出行人-通主表ID查询")
	@GetMapping(value = "/queryEaBusinessPerDtlByMainId")
	public Result<?> queryEaBusinessPerDtlListByMainId(@RequestParam(name="id",required=true) String id) {
		List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(id);
		return Result.OK(eaBusinessPerDtlList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param eaBusinessApply
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaBusinessApply eaBusinessApply) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<EaBusinessApply> queryWrapper = QueryGenerator.initQueryWrapper(eaBusinessApply, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<EaBusinessApply> queryList = eaBusinessApplyService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<EaBusinessApply> eaBusinessApplyList = new ArrayList<EaBusinessApply>();
      if(oConvertUtils.isEmpty(selections)) {
          eaBusinessApplyList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          eaBusinessApplyList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<EaBusinessApplyPage> pageList = new ArrayList<EaBusinessApplyPage>();
      for (EaBusinessApply main : eaBusinessApplyList) {
          EaBusinessApplyPage vo = new EaBusinessApplyPage();
          BeanUtils.copyProperties(main, vo);
          List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(main.getId());
          vo.setEaBusinessPerDtlList(eaBusinessPerDtlList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "出差申请单列表");
      mv.addObject(NormalExcelConstants.CLASS, EaBusinessApplyPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出差申请单数据", "导出人:"+sysUser.getRealname(), "出差申请单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<EaBusinessApplyPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EaBusinessApplyPage.class, params);
              for (EaBusinessApplyPage page : list) {
                  EaBusinessApply po = new EaBusinessApply();
                  BeanUtils.copyProperties(page, po);
                  eaBusinessApplyService.saveMain(po, page.getEaBusinessPerDtlList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
